﻿//#define VERBOSE
using System;
using MovieFactory.Core;
using MovieFactory.Core.Primitives;
using MovieFactory.RayEngine.Data;
using MovieFactory.RayEngine.PathTracer;
using MovieFactory.RayEngine.Samplers;

namespace MovieFactory.RayEngine.VertexFramework {
// ReSharper disable RedundantThisQualifier

    using RayInfo = RayData;



    public class Path : PathSampler {
        internal RgbSpectrum Throughput, Radiance;
        public PathTracerPathState PathState;
        public Sample Sample;

        protected int depth, tracedShadowRayCount, indexRef;
        protected float pathWeight;
        protected bool specularBounce;
        internal SurfaceSampler SurfaceSampler;

        protected RayEngineScene scene;

        public int MaxRaysPerPath {
            get;
            set;
        }

        public override void InitPath(PathBuffer buffer) {
            base.InitPath(buffer);
            this.scene = buffer.Scene;
            this.Radiance = new RgbSpectrum(0f);
            this.Throughput = new RgbSpectrum(1f);
            this.PathState = PathTracerPathState.EyeVertex;
            this.Sample = buffer.Sampler.GetSample();
            this.PathRay = new RayData ( scene.Camera.GetRay(Sample.imageX, Sample.imageY));
            this.RayIndex = -1;
            this.pathWeight = 1.0f;
            this.tracedShadowRayCount = 0;
            this.depth = 0;
            this.specularBounce = true;
        }

        public override bool FillRayBuffer(RayBuffer rayBuffer) {
            var leftSpace = rayBuffer.LeftSpace();
            if (((PathState == PathTracerPathState.EyeVertex) && (1 > leftSpace)) ||
            ((PathState == PathTracerPathState.ShadowRaysOnly) && (tracedShadowRayCount > leftSpace)) ||
            ((PathState == PathTracerPathState.NextVertex) && (tracedShadowRayCount + 1 > leftSpace)))
                return false;
            if (PathState != PathTracerPathState.ShadowRaysOnly)
                RayIndex = rayBuffer.AddRay(PathRay);
            return true;
        }


        public override void Advance(RayBuffer rayBuffer, IPathSamplerAggregator consumer, Action<PathSampler> onRestart) {
        }

        private RgbSpectrum SampleEnvironment(Vector vector) {
            return this.scene.SampleEnvironment(vector);
        }
    }
    // ReSharper restore RedundantThisQualifier
}